<!-- 监测车历史数据 -->
<template>
  <div class="newTest">
    <div class="title" style="border-bottom: 1px solid #eee">历史数据</div>
    <div class="searchBox">
      <el-form
        label-position="top"
        inline
        :model="searchForm"
        size="mini"
        style="max-height: 100px"
      >
        <el-form-item>
          <p slot="label" class="miniLabel">监测车编号</p>
          <el-select
            v-model="searchForm.vehicleNumber"
            placeholder="请选择编号"
            @change="changeNumber"
          >
            <el-option
              v-for="item in cartList"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <p slot="label" class="miniLabel">点位名称</p>
          <el-select
            v-model="searchForm.pointName"
            placeholder="请选择点位名称"
          >
            <el-option key="全部" label="全部" value="全部"></el-option>
            <el-option
              v-for="item in pointNameList"
              :key="item.id"
              :label="item.pointName"
              :value="item.pointName"
            ></el-option>
          </el-select>
          <!-- <el-input v-model="searchForm.pointName" placeholder="请输入内容"></el-input> -->
        </el-form-item>
        <el-form-item>
          <p slot="label" class="miniLabel">时间段</p>
          <el-date-picker
            v-model="dateSearch"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <p class="searchBtns">
            <el-button type="success" class="greenBtn" @click="searchClick()"
              >确定</el-button
            >
          </p>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <mergeTable
      :tableData="tableList"
      :tableConfig="tableConfig"
      :attributes="{
        border: true,
        headerCellStyle: {
          backgroundColor: 'transparent',
        },
        cellStyle: {
          height: '50px',
          backgroundColor: 'transparent',
        },
        headerRowStyle: {
          backgroundColor: 'transparent',
        },
        rowStyle: {
          backgroundColor: 'transparent',
        },
      }"
    >
      <el-table-column slot="operation" align="center" label="操作">
        <template slot-scope="{ row }">
          <el-button size="mini" type="primary" @click="addBtnClick(row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column slot="gmtCreate" align="center" label="监测时间">
        <template slot-scope="{ row }">
          <div>
            <span>{{ row.gmtCreate }}</span>
            至
            <span v-if="row.lasttime">{{ row.lasttime }}</span>
            <span v-else>{{ row.addlasttime }}</span>
          </div>
        </template>
      </el-table-column>
    </mergeTable>
    <v-paging @setCurrent="setPage" @setCurren="setNum" :total="total" />
    <el-dialog
      :visible.sync="dilogVisible"
      :modal-append-to-body="false"
      width="70%"
      ref="dialog"
      @close="closeDialog"
    >
      <div class="searchBox" v-loading="hisLoading">
        <el-form
          label-position="top"
          inline
          :model="dilogSearchForm"
          size="mini"
          style="max-height: 100px"
        >
          <el-form-item>
            <p slot="label" class="miniLabel">点位名称</p>
            <el-input
              v-model="dilogSearchForm.pointName"
              class="form-input"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item>
            <p slot="label" class="miniLabel">时间段</p>
            <el-date-picker
              v-model="dateDetailSearch"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerStartOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <p class="searchBtns">
              <el-button type="success" class="greenBtn" @click="submitSearch()"
                >筛选</el-button
              >
              <el-button type="success" class="greenBtn" @click="exportExcel"
                >导出</el-button
              >
            </p>
          </el-form-item>
        </el-form>
      </div>
      <div class="showType">
        <div class="title" style="border-bottom: 1px solid #eee">
          <el-radio-group
            v-model="showType"
            size="small"
            @change="showTypeChange"
            style="margin-left: 12px"
          >
            <el-radio-button label="图表"></el-radio-button>
            <el-radio-button label="表格"></el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="dataChartCnt" v-if="showType === '图表'">
        <div class="dataChartBox">
          <div
            class="chart"
            v-for="(option, index) in lineOptions"
            :key="index"
            v-show="option.show"
          >
            <el-button
              size="mini"
              class="openchart"
              @click="openDetailChart(option)"
            >
              <i class="iconfont iconquanping"></i>
            </el-button>
            <lineChart
              v-show="option.show"
              :option="option"
              :isShow="option.show"
            ></lineChart>
          </div>
          <p class="noData" v-show="!isNoData">暂无数据</p>
        </div>
      </div>
      <div class="hisDataTable" v-if="showType === '表格'">
        <tableList
          :hisDataList="hisDataList"
          :factorField="factorField"
          :factorStatus="factorStatus"
          :dataTypeShow="'hour'"
        ></tableList>
        <v-paging
          @setCurrent="setListNum"
          @setCurren="setListPage"
          :total="totalpage"
        />
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="detailChartVisible"
      width="80%"
      custom-class="historyChart"
      :modal-append-to-body="false"
    >
      <div class="deatailChartCnt">
        <div class="deatailChart" id="deatailChart"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCartList,
  getHistoricalDataList,
  getHistoricalData,
  downHistoryDataListisExcel,
  getPointNames,
} from "@/http/api";
import common from "@/plugins/common";
import standard from "../plugins/standard.js";
import lineChart from "../components/charts.vue";
import { mapGetters, mapActions } from "vuex";
import tableList from "@/components/tableList.vue";
export default {
  data() {
    return {
      cartList: [],
      pointNameList: [],
      factorField: [],
      factorStatus: {},
      tableList: [],
      searchForm: {
        lastTime: "",
        pageNum: 1,
        pageSize: 12,
        pointName: null,
        startTime: "",
        vehicleNumber: "",
      },
      total: null,
      dateSearch: [
        new Date().setMonth(new Date().getMonth() - 1),
        new Date().setMonth(new Date().getMonth()),
      ],
      dateDetailSearch: [],
      searchResult: [],
      tableConfig: [
        { prop: "vehicleNumber", label: "监测车编号", align: "center" },
        { prop: "gmtCreate", slot: "gmtCreate", align: "center" },
        { prop: "pointName", label: "点位名称", align: "center" },
        { prop: "address", label: "地理位置", align: "center" },
        { prop: "streetName", label: "所属街道办", align: "center" },
        { prop: "pollutionFactor", label: "监测因子", align: "center" },
        { prop: "principal", label: "站点负责人", align: "center" },
        { prop: "personPhone", label: "负责人联系方式", align: "center" },
        { prop: "unit", label: "运维单位", align: "center" },
        { prop: "operation", slot: "operation" },
      ],
      // 查看弹窗
      hisLoading: false,
      dilogSearchForm: {
        pointName: "",
        pointNumbering: "",
        vehicleNumber: "",
        isExcel: "no",
      },
      standard,
      dilogVisible: false,
      exportOption: {},
      showType: "图表",
      lineOptions: {},
      detailChart: null,
      detailChartVisible: false,
      hisDataList: [],
      historyDataTotal: 0,
      // 导出表格
      exportExcelVisible: false,
      tableRow: {},
      pageNum: 1,
      totalpage: 0,
      pageSize: 12,
      row: {},
      isNoData: true,
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > Date.now();
        },
      },
      pickerStartOptions: {
        disabledDate: (time) => {
          if (this.row.lasttime === null) {
            return (
              time.getTime() > new Date().getTime() ||
              time.getTime() + 24 * 3600 * 1000 <
                new Date(this.row.gmtCreate).getTime()
            );
          } else {
            return (
              time.getTime() > new Date(this.row.lasttime).getTime() ||
              time.getTime() + 24 * 3600 * 1000 <
                new Date(this.row.gmtCreate).getTime()
            );
          }
        },
      },
    };
  },
  created() {
    // 获取监测车编号
    this.getCartListAction();
  },
  components: {
    lineChart,
    tableList,
  },
  computed: {
    ...mapGetters({
      userInfo: "getUserInfo",
      hiddenLeftNav: "getHiddenLeftNav",
    }),
    // isNoData() {
    //   return !Object.values(this.lineOptions)
    //     .map((v) => v.show)
    //     .includes(true);
    // },
  },
  methods: {
    // 选择监测车点位变化
    async changeNumber(val) {
      this.pointNameList = [];
      let res = await getPointNames({
        vehicleNumber: val,
      });
      res.data.forEach((data, index) => {
        this.pointNameList.push({
          pointName: data,
          id: index,
        });
      });
    },
    closeDialog() {
      this.showType = "";
    },
    // dilogChangeLastTime(val) {
    //   this.dilogSearchForm.lastTime = val + " 00:00:00";
    // },
    // dilogChangeStartTime(val) {
    //   this.dilogSearchForm.startTime = val + " 00:00:00";
    // },
    // 获取监测车编号
    async getCartListAction() {
      let data = await getCartList();
      this.searchForm.vehicleNumber = data.data[0].name;
      let res = await getPointNames({
        vehicleNumber: this.searchForm.vehicleNumber,
      });
      res.data.forEach((data, index) => {
        this.pointNameList.push({
          pointName: data,
          id: index,
        });
      });
      this.getHistoricalDataListAction();
      this.cartList = data.data;
    },
    // 获取监测车历史数据
    async getHistoricalDataListAction() {
      (this.searchForm.startTime = this.$getLocalTime(
        new Date(this.dateSearch[0])
      )),
        (this.searchForm.lastTime = this.$getLocalTime(
          new Date(this.dateSearch[1])
        ));
      var params = {
        startTime: this.searchForm.startTime,
        pageNum: this.searchForm.pageNum,
        pageSize: this.searchForm.pageSize,
        lastTime: this.searchForm.lastTime,
        vehicleNumber: this.searchForm.vehicleNumber,
      };
      if (this.searchForm.pointName === "全部") {
        Object.assign(params, { pointName: null });
      } else {
        Object.assign(params, { pointName: this.searchForm.pointName });
      }
      let data = await getHistoricalDataList(params);
      this.total = data.data.total;
      data.data.data.forEach((data) => {
        if (!data.lasttime) {
          data.addlasttime = this.$getLocalTime(new Date());
        }
      });
      this.tableList = data.data.data;
    },
    // 确定搜索
    searchClick() {
      if (this.searchForm.vehicleNumber.length > 0) {
        this.getHistoricalDataListAction(this.searchForm);
      }
    },
    //设置条数
    setNum(val) {
      this.searchForm.pageSize = val;
      this.getHistoricalDataListAction(this.searchForm);
    },
    //设置页数
    setPage(val) {
      this.searchForm.pageNum = val;
      this.getHistoricalDataListAction(this.searchForm);
    },
    // 查看
    async addBtnClick(row) {
      this.dilogVisible = true;
      this.showType = "图表";
      this.row = row;
      setTimeout(() => {
        let windowWidth = document.documentElement.clientWidth;
        let dialogWidth = this.$refs.dialog.$refs.dialog.clientWidth;

        let left;
        if (this.hiddenLeftNav) {
          left = 0;
        } else {
          left =
            (windowWidth - dialogWidth) / 2 - (windowWidth * 0.3 - 230) / 2;
        }
        this.$refs.dialog.$refs.dialog.style.left = left + "px";
      }, 100);
      if (row.lasttime === null) {
        if (
          new Date().getTime() - new Date(row.gmtCreate).getTime() <
          518400000
        ) {
          this.dateDetailSearch = [
            common.changeDateToString(new Date(row.gmtCreate)),
            common.changeDateToString(new Date()),
          ];
        } else {
          this.dateDetailSearch = [
            common.changeDateToString(
              new Date(new Date().getTime() - 518400000)
            ),
            common.changeDateToString(new Date()),
          ];
        }
      } else {
        if (
          new Date(row.lasttime).getTime() - new Date(row.gmtCreate).getTime() <
          518400000
        ) {
          this.dateDetailSearch = [
            common.changeDateToString(new Date(row.gmtCreate)),
            common.changeDateToString(new Date(row.lasttime)),
          ];
        } else {
          this.dateDetailSearch = [
            common.changeDateToString(
              new Date(new Date(row.lasttime).getTime() - 518400000)
            ),
            common.changeDateToString(new Date(row.lasttime)),
          ];
        }
      }
      this.dilogSearchForm = {
        pointName: row.pointName,
        pointNumbering: row.pointNumbering,
        vehicleNumber: row.vehicleNumber,
      };
      this.tableRow = row;
      this.submitSearch();
    },
    // 图表和表格的切换
    async showTypeChange() {
      this.submitSearch();
    },
    //获取图表和表格的数据
    async submitSearch() {
      this.hisLoading = true;
      var params = {
        pointName: this.dilogSearchForm.pointName,
        startTime: this.dateDetailSearch[0] + " 00:00:00",
        lastTime: this.dateDetailSearch[1] + " 23:59:59",
        pointNumbering: this.dilogSearchForm.pointNumbering,
        vehicleNumber: this.dilogSearchForm.vehicleNumber,
      };
      if (this.showType === "图表") {
        let res = await getHistoricalData(params);
        this.searchResult = res.data;
        this.configLineChart();
      } else if (this.showType === "表格") {
        let data = await getHistoricalData(
          Object.assign(params, {
            pageSize: this.pageSize,
            pageNum: this.pageNum,
          })
        );
        this.hisDataList = data.data.data;
        this.factorField = [];
        data.data.factorMessage.forEach((item) => {
          if (Object.keys(data.data.factorField).includes(item.name)) {
            this.factorField.push({
              prop: data.data.factorField[item.name],
              label: item.name + (item.name === "pH" ? "" : " mg/L"),
              devStatus: item.name,
              standardValue: item.standardValue,
              factorLimit:
                item.name === "pH"
                  ? "±" + item.factorLimit + "L"
                  : item.factorLimit + "L",
            });
          }
        });
        this.factorStatus = data.data.factorStatus;
        this.totalpage = data.data.totalpage;
      }
      this.hisLoading = false;
    },
    configLineChart() {
      let chartData = this.searchResult.data || [];
      let newOptions = {};
      let translate = {};
      let standard = {};
      let lineOptions = {};
      this.searchResult.factorMessage.forEach((item, index) => {
        if (this.searchResult.factorField[item.name]) {
          translate[this.searchResult.factorField[item.name]] = item.name;
          standard[this.searchResult.factorField[item.name]] =
            item.standardValue;
          newOptions[this.searchResult.factorField[item.name]] = new Array();
          lineOptions[this.searchResult.factorField[item.name]] = {};
        }
        if (this.searchResult.factorMessage.length - 1 === index) {
          newOptions["xAxis"] = new Array();
        }
      });
      for (let i = 0, len = chartData.length; i < len; i++) {
        for (var key in newOptions) {
          if (key !== "xAxis") {
            newOptions[key].push(chartData[i][key]);
          } else {
            newOptions[key].push(chartData[i].gmtMonitor);
          }
        }
      }
      let defaultOption = {
        show: true,
        grid: {
          left: "11%",
        },
        title: {
          // text: 'pH/总磷',
          left: "center",
          top: 10,
          textStyle: {
            fontSize: 14,
          },
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          // data: newOptions.xAxis,
          type: "category",
          axisLabel: {
            formatter: (value) => value.replace(/ /, "\n"),
          },
          axisTick: {
            inside: true,
            alignWithLabel: true,
          },
        },
        yAxis: {
          name: "mg/L",
          splitLine: {
            show: false,
          },
          axisTick: {
            inside: true,
          },
        },
        series: [
          {
            type: "line",
            stact: "总量",
            smooth: true,
            large: true,
            data: newOptions.ph,
            areaStyle: {},
            itemStyle: {},
          },
        ],
      };

      let optionColor = {
        ph: "#A3A6F6",
        COD: "#F47FC1",
        ammoniaNitrogen: "#5BB0F0",
        phosphorus: "#FF8282",
        nitrogen: "#F0D65B",
        nickel: "#67EBAB",
        cuprum: "#F09C5B",
        chromium: "#5DD3EC",
        prussiate: "#D4A3F6",
        zinc: "#5BF0E6",
      };
      this.$nextTick(() => {
        for (let i in lineOptions) {
          lineOptions[i] = common.deepClone(defaultOption);
          lineOptions[i].series[0].itemStyle.color = optionColor[i];
          lineOptions[i].series[0].areaStyle = {
            color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: optionColor[i],
              },
              {
                offset: 1,
                color: "rgb(255, 255, 255)",
              },
            ]),
          };
          lineOptions[i].title.text = translate[i];
          lineOptions[i].xAxis.data = newOptions.xAxis.reverse();
          lineOptions[i].series[0].data = newOptions[i];
          lineOptions[i].series[0].name = translate[i];
          lineOptions[i].series[0].markLine = {
            name: translate[i],
            silent: true,
            large: true,
            symbol: "none",
            data: [
              {
                yAxis: standard[i],
              },
            ],
            label: {
              position: "end",
              // formatter: '标准线:{c}'
            },
            lineStyle: {
              color: "#e46f6f",
            },
          };

          lineOptions[i].show =
            newOptions[i].filter((d) => d !== null).length > 0;
        }

        // ph special handle
        if (lineOptions["ph"]) {
          lineOptions["ph"].yAxis.max = 14; //ph
          lineOptions["ph"].yAxis.maxInterval = 2;
          lineOptions["ph"].yAxis.name = "";
          lineOptions["ph"].series[0].markLine.data = [
            {
              yAxis: standard["ph"].split("~")[1],
            },
            {
              yAxis: standard["ph"].split("~")[0],
            },
          ];
        }
        this.lineOptions = lineOptions;
        this.isMeanNoData = Object.values(this.lineOptions)
          .map((v) => v.show)
          .includes(true);
      });
    },
    openDetailChart(option) {
      this.detailChartVisible = true;
      this.$nextTick(() => {
        this.detailChart = this.$echarts.init(
          document.getElementById("deatailChart")
        );
        this.initDeatailChart(option);
      });
    },
    initDeatailChart(option) {
      this.detailChart.setOption({
        grid: {
          bottom: 80,
        },
        title: {
          text: option.title.text,
          left: "center",
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          axisLabel: {
            formatter: (value) => value.replace(/ /, "\n"),
          },
          axisTick: {
            inside: true,
            alignWithLabel: true,
          },
          data: option.xAxis.data,
        },
        yAxis: [
          {
            name: option.yAxis.name,
            splitLine: {
              show: false,
            },
            axisTick: {
              inside: true,
              show: false,
            },
            max: option.title.text === "pH" ? 14 : null,
            maxInterval: option.title.text === "pH" ? 2 : null,
          },
        ],
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: false,
            },
            saveAsImage: {
              pixelRatio: 2,
            },
          },
        },
        dataZoom: [
          {
            type: "slider",
            end: 50,
          },
        ],
        series: [
          {
            name: option.series[0].name,
            type: "line",
            smooth: true,
            large: true,
            data: option.series[0].data,
            itemStyle: {
              color: option.series[0].itemStyle.color,
            },
            areaStyle: {
              color: option.series[0].areaStyle.color,
            },
            markLine: option.series[0].markLine,
          },
        ],
      });
    },
    tableRowStyle({ rowIndex }) {
      if (rowIndex % 2 > 0) {
        return {
          backgroundColor: "#f6f6f6",
        };
      } else {
        return {
          backgroundColor: "#fff",
        };
      }
    },

    async exportExcel() {
      var params = {
        vehicleNumber: this.dilogSearchForm.vehicleNumber,
        pointNumbering: this.dilogSearchForm.pointNumbering,
        startTime: this.dateDetailSearch[0] + " 00:00:00",
        lastTime: this.dateDetailSearch[1] + " 23:59:59",
      };
      const message = this.$message({
        message: "正在导出数据, 请稍后",
        duration: 0,
      });
      this.dilogSearchForm.isExcel = "yes";
      await downHistoryDataListisExcel(params);
      this.dilogSearchForm.isExcel = "no";
      message.close();
    },
    //设置条数
    setListNum(val) {
      this.pageSize = val;
      this.submitSearch({ pageSize: this.pageSize, pageNum: this.pageNum });
    },
    //设置页数
    setListPage(val) {
      this.pageNum = val;
      this.submitSearch({ pageSize: this.pageSize, pageNum: this.pageNum });
    },
  },
};
</script>

<style scoped>
.upload-demo {
  display: flex;
}

/deep/ .el-dialog__headerbtn {
  top: 10px !important;
}
#dialog-footer {
  display: flex !important;
  justify-content: center;
}

.newTest .el-dialog .el-dialog__footer {
  display: flex !important;
  justify-content: center;
  color: red;
}

.newTest {
  background: #fff;
  min-height: 100%;
  padding: 0 20px 0 20px;
}

.newTest .title {
  position: relative;
  left: 15px;
  line-height: 70px;
  font-size: 16px;
}

.newTest .title::before {
  content: "";
  position: absolute;
  left: -15px;
  width: 4px;
  height: 20px;
  top: 25px;
  background-color: #2399ff;
}

.searchBox {
  padding: 20px 20px 0;
  margin-bottom: 20px;
  background-color: #fff;
}

.searchBox .miniLabel {
  line-height: 0;
}

.searchBtns {
  margin-top: 19px;
}

.el-dialog {
  z-index: 3000 !important;
}

.historyData {
  min-height: 100%;
}

.searchBox {
  padding: 20px 20px 0px 0px;
  margin-bottom: 20px;
  background-color: #fff;
}

.searchBox .miniLabel {
  line-height: 0;
}
.el-dialog {
  z-index: 3000 !important;
}
.dataChartBox {
  display: flex;
  flex-flow: row wrap;
  /* justify-content: space-between; */
  justify-content: flex-start;
  width: 100%;
}

.dataChartBox .chart {
  position: relative;
  width: 31%;
  margin: 0 1%;
  height: 300px;
  min-height: 300px;
  background: #fff;
  margin-bottom: 20px;
}

.openchart .chart .openchart {
  position: absolute;
  right: 12px;
  top: 12px;
  z-index: 1;
}

.dataChartBox .chart .openchart i {
  font-size: 12px;
}

.dataChartCnt {
  background-color: #fff;
  padding: 0 20px;
}

.hisDataTable {
  background-color: #fff;
  padding: 0 20px 20px 20px;
}

.searchBtns {
  margin-top: 19px;
}

.deatailChartCnt {
  width: 100%;
  height: 450px;
}

.deatailChartCnt .deatailChart {
  width: 100%;
  height: 100%;
}

.noData {
  width: 100%;
  line-height: 60px;
  text-align: center;
  color: #909399;
}

.showType {
  background-color: #fff;
  padding: 20px;
}
/* .abow_dialog {
  display: flex;
  justify-content: center;
  align-items: Center;
  overflow: hidden;
}

.abow_dialog .el-dialog {
  position: absolute;
  left: 0;
  top: 54px;
  bottom: 0;
  right: 0;
  padding: 0;
  z-index: 1;
  overflow: hidden;
  overflow-y: auto;
} */
</style>
<style>
.historyChart .el-dialog__header {
  background-image: none;
}

.historyChart .el-dialog__headerbtn .el-dialog__close {
  color: #666;
}
</style>
